package com.mousycoder.redis.service;

import com.mousycoder.redis.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * TODO
 *
 * @author mousycoder
 * @version 1.0
 * @date 2022/4/25 12:09 PM
 */
@Service
public class SeckillService {

    public static final String secStartPrefix = "skuId_start_";
    public static final String secAccess = "skuId_access_";
    public static final String secCount = "skuId_count_";
    public static final String filterName = "skuId_bloomfilter";
    public static final String bookedName = "skuId_booked_";

    @Resource
    private RedisService redisService;

    public String seckill(int uid,int skuId){
        String isStart = (String) redisService.get(secStartPrefix + skuId);
        if (StringUtils.isBlank(isStart)){
            return "还未开始";
        }
        if (isStart.contains("_")){
            Integer isStartInt = Integer.parseInt(isStart.split("_")[0]);
            Integer startTime = Integer.parseInt(isStart.split("_")[1]);

            if (isStartInt == 0){
                if (startTime > getNow()){
                    return "还未开始";
                }else {
                    redisService.set(secStartPrefix + skuId,1+"");
                }
            }else {
                return "系统异常";
            }
        }else {
            if (Integer.parseInt(isStart) != 1){
                return "系统异常";
            }
        }

        String skuIdAccessName = secAccess + skuId;
        Integer accessNumInt = 0;
        String accessNum = (String) redisService.get(skuIdAccessName);

        if (StringUtils.isNotBlank(accessNum)){
            accessNumInt = Integer.parseInt(accessNum);
        }

        String skuIdCountName = secCount + skuId;
        Integer countNumInt = Integer.parseInt((String) redisService.get(skuIdCountName));

        if (countNumInt * 1.2 < accessNumInt) {
            return "抢购已经完成，欢迎下次再来";
        }else {
            redisService.incr(skuIdAccessName);
        }

        if (redisService.bloomFilterExists(filterName,uid)){
            return "您已经抢购过该商品，请勿重复下发";
        }else {
            redisService.bloomFilterAdd(filterName,uid);
        }

        Boolean isSuccess = redisService.getAndIncrLua(bookedName + skuId);
        if (isSuccess){
            return "恭喜抢购成功";
        }else {
            return "抢购结束，欢迎下次再来";
        }
    }

    private long getNow() {
        return System.currentTimeMillis() / 1000;
    }
}
